const { sequelize } = require("../db/index")
const { DataTypes, Model } = require("sequelize")
const User = require("./user_model")
const Cleaner = require("./cleaner_model")
const moment = require('moment');

class StoreHouse extends Model {
  static async hasCate(id) {
    const cate = await Cate.findOne({ where: { id } })
    if (cate === null) {
      return false
    } else {
      return true
    }
  }
  static async createCate({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content }) {
    const goods = await Goods.create({ goods_name, full_goods_name, cat_id, attr, stock, sales, weight, desc, ord, store_id, is_hot, is_recommend, status, is_delete, slider_image, content })
    return goods
  }
  static async addAdmin(buildingId, userId) {
    try {
      const cate = await Cate.findOne({ where: { id: buildingId } })
      const user = await User.findOne({ where: { id: userId } })
      const result = await cate.addAdmin(user)
      return result
    } catch (e) {
      throw new Error("已存在该管理员，添加失败")
    }
  }
  static async addCleaner(buildingId, cleanerId) {
    try {
      const cleaner = await Cleaner.findOne({ where: { id: cleanerId } })
      cleaner.buildingId = buildingId
      return await cleaner.save()
    } catch (e) {
      throw new Error("添加保洁员失败")
    }
  }
  static async addFloor(buildingId, floor) {
    try {
      floor.buildingId = buildingId
      return await floor.save()
    } catch (error) {
      console.log(error)
    }
  }
}

StoreHouse.init(
  {
    id: {
      comment: "仓库ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    store_id: {
      comment: "门店ID",
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: false,
      allowNull: false
    },
    store_house_name: {
      comment: "仓库名称",
      type: DataTypes.STRING,
      autoIncrement: false,
      allowNull: false
    },
    area_address: {
      comment: "详细地址",
      type: DataTypes.NUMBER,
      autoIncrement: false,
      allowNull: false
    },
    update_time: {
      comment: "更新时间",
      type: DataTypes.STRING,
      get() {
        return moment(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  },
  {
    sequelize,
    modelName: "sp_store_house",
    freezeTableName: true,
    paranoid: false,
    timestamps: false
  }
)

module.exports = StoreHouse
